package com.yunhe.option.service.base.impl;

import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.exception.UniqueConstraintsException;
import com.yunhe.common.util.QueryUtil;
import com.yunhe.common.util.StringUtil;
import com.yunhe.option.domain.base.IndustryCategory;
import com.yunhe.option.repository.base.IndustryCategoryRepository;
import com.yunhe.option.service.base.IndustryCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Optional;

/**
 * 企业行业类型Service
 * @desc 企业行业类型服务类实现
 * @author anmeiyi
 */
@Service
public class IndustryCategoryServiceImpl implements IndustryCategoryService {
    @Autowired
    private IndustryCategoryRepository industryCategoryRepository;

    private void processBeforeSave(IndustryCategory industryCategory)
            throws ArgumentErrorException, UniqueConstraintsException {
        //判断企业行业类型代码、编号、标题是否为空
        if(industryCategory.getCode() == null
                || StringUtil.isEmpty(industryCategory.getName())
                || StringUtil.isEmpty(industryCategory.getTitle())) {
            throw new ArgumentErrorException("企业行业类型代码、编号、标题不能为空");
        }
        //判断代码是否已存在
        IndustryCategory categoryByCode = this.findByCode(industryCategory.getCode());
        if(categoryByCode != null) {
            if(industryCategory.getId() == null || categoryByCode.getId().longValue() != industryCategory.getId().longValue()) {
                throw new UniqueConstraintsException("该企业行业类型代码已存在");
            }
        }
        //判断编号是否已存在
        IndustryCategory categoryByName = this.findByName(industryCategory.getName());
        if(categoryByName != null) {
            if(industryCategory.getId() == null || categoryByName.getId().longValue() != industryCategory.getId().longValue()) {
                throw new UniqueConstraintsException("该企业行业类型编号已存在");
            }
        }
        //如果序号为空，则默认等于代码
        if(industryCategory.getSn() == null && industryCategory.getCode() != null) {
            industryCategory.setSn(industryCategory.getCode());
        }
    }

    /**
     * 新增企业行业类型
     * @param industryCategory 企业行业类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public IndustryCategory createIndustryCategory(IndustryCategory industryCategory)
            throws ArgumentErrorException, UniqueConstraintsException {
        industryCategory.setId(null);
        processBeforeSave(industryCategory);
        return industryCategoryRepository.save(industryCategory);
    }

    /**
     * 删除企业行业类型
     * @param industryCategoryId 企业行业类型Id
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public void deleteIndustryCategory(Long industryCategoryId) {
        industryCategoryRepository.deleteById(industryCategoryId);
    }

    /**
     * 更新企业行业类型(全部字段）
     * @param industryCategory 企业行业类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public IndustryCategory updateIndustryCategory(IndustryCategory industryCategory)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        boolean exists = industryCategory.getId() != null && industryCategoryRepository.existsById(industryCategory.getId());
        if(!exists) {
            throw new ObjectNotFoundException("找不到ID为" + industryCategory.getId() + "的企业行业类型");
        }
        processBeforeSave(industryCategory);
        return industryCategoryRepository.save(industryCategory);
    }

    /**
     * 更新企业行业类型（部分字段）
     * @param industryCategoryId 企业行业类型对象
     * @param code
     * @param name
     * @param title
     * @param sn
     * @param activity
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public IndustryCategory updateIndustryCategory(Long industryCategoryId, Long code, String name, String title, Long sn, Boolean activity)
            throws ArgumentErrorException, UniqueConstraintsException, ObjectNotFoundException {
        IndustryCategory industryCategory = this.findByIndustryCategoryId(industryCategoryId);
        if(industryCategory == null) {
            throw new ObjectNotFoundException("找不到ID为" + industryCategoryId + "的企业行业类型");
        }
        Optional.ofNullable(code).ifPresent(industryCategory::setCode);
        Optional.ofNullable(name).ifPresent(industryCategory::setName);
        Optional.ofNullable(title).ifPresent(industryCategory::setTitle);
        Optional.ofNullable(sn).ifPresent(industryCategory::setSn);
        Optional.ofNullable(activity).ifPresent(industryCategory::setActivity);
        processBeforeSave(industryCategory);
        return industryCategoryRepository.save(industryCategory);
    }

    /**
     * 获得全部企业行业类型对象
     */
    @Transactional(rollbackFor = Exception.class, transactionManager = "transactionManager")
    public Iterable<IndustryCategory> findIndustryCategories() {
        return industryCategoryRepository.findAll(QueryUtil.defaultSort());
    }

    /**
     * 根据编号获得企业行业类型对象
     * @param name
     */
    private IndustryCategory findByName(String name) {
        return industryCategoryRepository.findByName(name);
    }

    /**
     * 根据代码获得企业行业类型对象
     * @param code
     */
    private IndustryCategory findByCode(Long code) {
        return industryCategoryRepository.findByCode(code);
    }

    /**
     * 根据ID获得企业行业类型对象
     * @param industryCategoryId
     * @return
     */
    private IndustryCategory findByIndustryCategoryId(Long industryCategoryId) {
        return industryCategoryRepository.findById(industryCategoryId).orElse(null);
    }
}
